package pt.ipl.isel.deetc.leic.pdm.g12.yamba;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import winterwell.jtwitter.Twitter;
import winterwell.jtwitter.Twitter.User;
import android.app.Service;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;
import android.widget.Toast;

public class UserInfoPullService extends Service {
	public static final int USER_INFO = 0;
	final Messenger messenger = new Messenger(new IncomingHandler());
	
	class IncomingHandler extends Handler{
		@Override
		public void handleMessage(Message msg) {
			switch(msg.what){
			case USER_INFO:
				sendResp(msg);
				break;
			default:
				super.handleMessage(msg);
			}
		}
		
		private BitmapDrawable getPicture(URL url){
			Bitmap x = null;
			
			if(url != null){
				try {
				    HttpURLConnection connection = (HttpURLConnection)url.openConnection();
				    connection.connect();
				    InputStream input;
					input = connection.getInputStream();
					x = BitmapFactory.decodeStream(input);
				} catch (IOException e) {
					Toast.makeText(getApplicationContext(), R.string.profilePicture_error, Toast.LENGTH_LONG);
					Log.e("PDM", "Error getting profile picture", e);
				}
			}
			
		    return new BitmapDrawable(x);
		}
		
		private void sendResp(Message msg){
			try {
				Message resp = Message.obtain();
				Twitter twitter = ((YambaPdmApp)getApplication()).getTwitter();
				User user = twitter.getUser(twitter.getScreenName());
				
				URL url = null;
				try {
					url = user.getProfileImageUrl().toURL();
				} catch (MalformedURLException e) {
					Log.e("PDM", "Malformed URL", e);
				}
		
				Bundle b = new Bundle();
				b.putParcelable("UserInfo", new UserInfo(user.getScreenName(), user.getStatusesCount(), user.getFriendsCount(), user.getFollowersCount(), getPicture(url)));
				b.setClassLoader(UserInfo.class.getClassLoader());
				resp.setData(b);
				
				msg.replyTo.send(resp);
			} catch (RemoteException e) { 
				Toast.makeText(getApplicationContext(), R.string.response_error, Toast.LENGTH_LONG);
				Log.e("PDM", "Error @ UserInfoPullService.sendResp()", e);
			}
		}
	}
	
	@Override
	public IBinder onBind(Intent intent) {
		Log.i("PDM", "UserInfoPullService onBind");
		return messenger.getBinder();
	}

}
